<template>
  <el-dialog
    title="提示"
    :visible="dialogVisible"
    width="30%"
    @close="closeDialog"
  >
    <template #default>
      <el-form ref="roleForm" label-width="120px" :model="roleInfo" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleInfo.name" style="width:80%" placeholder="1-12个字符" />
        </el-form-item>

        <el-form-item label="角色介绍" prop="description">
          <el-input v-model="roleInfo.description" style="width:80%" placeholder="1-300个字符" type="textarea" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click.prevent="addRole">确 定</el-button>
      </span>
    </template>

  </el-dialog>

</template>

<script>
import { editRoleFormAPI, updateRoleInfoAPI } from '@/api/settings'
export default {
  name: 'AddRole',
  props: {
    dialogVisible: {
      type: Boolean
    }
  },
  data() {
    return {
      roleInfo: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称必填', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色介绍必填', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {

    // 关闭弹窗
    closeDialog() {
      this.$emit('closeDialog')
      this.$refs.roleForm.resetFields()
      this.roleInfo = {
        name: '',
        description: '',
        id: ''
      }
    },
    addRole() {
      this.$refs.roleForm.validate(async(valid) => {
        if (!valid) return
        if (this.roleInfo.id) {
          await updateRoleInfoAPI(this.roleInfo)
        }
        // this.$http.post当全局插件注册在plugin里边
        await this.$http.post('/sys/role', this.roleInfo)
        this.$message.success(`${this.roleInfo.id ? '编辑' : '添加'}成功`)
        this.$emit('update-list')
        this.closeDialog()
      })
    },
    cancel() {
      this.closeDialog()
    },
    async roleInfoBackFill(id) {
      const res = await editRoleFormAPI(id)
      this.roleInfo = res
    }
  }
}
</script>

<style>
</style>
